import Vue from 'vue'
import config from '@/config/index.js';

// 1. 防抖
export const debounce = (func, wait) => {
  let timeout;
  return function(...args) {
    clearTimeout(timeout);
    timeout = setTimeout(() => {
      func.apply(this, args);  // 保证 `this` 上下文为 Vue 组件
    }, wait);
  };
};

// 2. 节流
export const throttle = (func, delay) => {
  let lastCall = 0;
  return function(...args) {
    const now = Date.now();
    if (now - lastCall >= delay) {
      lastCall = now;
      func.apply(this, args);  // 保证 `this` 上下文为 Vue 组件
    }
  };
};

// 格式化价格
export const formatPrice = (price) => {
	if (!price) return { integerPart: '0', decimalPart: '.00' };
	const parts = parseFloat(price).toFixed(2).split('.');
	return {
	  integerPart: parts[0],
	  decimalPart: `.${parts[1]}`
	};	    
}

Vue.prototype.$debounce = debounce;
Vue.prototype.$throttle = throttle;
Vue.prototype.$formatPrice = formatPrice;
Vue.prototype.$host = process.env.VUE_APP_BASE_URL;

// 3. 保留二位小数
export const baoliu2 = (num) => {
    return Number(val).toFixed(2)
}

// 4. 获取元素高度

/**
	getElementHeight('#myElement').then(height => {
	  console.log('元素高度为：', height);
	}).catch(error => {
	  console.error(error);
	});

	// 在组件中获取元素高度
	getElementHeight('#myElement', this).then(height => {
	  console.log('组件中元素高度为：', height);
	}).catch(error => {
	  console.error(error);
	});
 */
export const getElementHeight = (selector, context = null) => {
  return new Promise((resolve, reject) => {
    // 创建选择器查询对象
    let query = null;

    if (context) {
      query = uni.createSelectorQuery().in(context);
    } else {
      query = uni.createSelectorQuery();
    }

    query
      .select(selector)
      .boundingClientRect(rect => {
        if (rect) {
          resolve(rect.height); // 返回高度
        } else {
          reject('元素未找到');
        }
      })
      .exec();
  });
};


 
/**
 * @description: 检测订阅消息是否开启，并授权
 * @date 2023/06/01
 * @param key {String} 订阅消息模板KEY[ID]， 可判断是否开启了该订阅消息授权
 */

export const isOpenSubscribeToNewsAndAuth = (key) => {
    return new Promise((re, rj) => {
        wx.getSetting({
            withSubscriptions: true,
            success: ({subscriptionsSetting}) => {
                if (!subscriptionsSetting) {
                    return rj(new Error('无法获取订阅消息对象，可能版本库兼容原因'))
                }
                if (!subscriptionsSetting.mainSwitch) {
                    return rj(new Error('订阅消息未打开'))
                }
                if (key && subscriptionsSetting.itemSettings[key] != 'accept') {
                    return rj(new Error(`模板消息：${key} 未开启`))
                }
                re(subscriptionsSetting.itemSettings)
            },
            fail: err => rj(err)
        })
    })
}

/**
 * 保存图片至本地相册
 * @param url 图片地址
 * @param imageName 图片名称
 */
export const downloadImage = (url, imageName = 'qr') => {
  // #ifdef H5
  let image = new Image();
  // 解决跨域 Canvas 污染问题
  image.setAttribute("crossOrigin", "anonymous");
  image.onload = function () {
    let canvas = document.createElement("canvas");
    canvas.width = image.width;
    canvas.height = image.height;
    let context = canvas.getContext("2d");
    context.drawImage(image, 0, 0, image.width, image.height);
    let url = canvas.toDataURL("image/png"); //得到图片的base64编码数据
    let a = document.createElement("a"); // 生成一个a元素
    let event = new MouseEvent("click"); // 创建一个单击事件
    a.download = imageName; // 设置图片名称
    a.href = url; // 将生成的URL设置为a.href属性
    a.dispatchEvent(event); // 触发a的单击事件
  };
  image.src = url;
  // #endif
  // #ifdef APP-PLUS
  uni.saveImageToPhotosAlbum({
    filePath: url,
    success: () => {
      toast('图片已成功保存到本地相册')
    },
    fail: () => {
      // fail方法里面还可以细分用户是否有开通相册权限以提示用户
      toast('图片保存失败！请检查APP访问照片权限是否打开，并稍后再试')
    }
  });
  // #endif
}